﻿using System;
using System.IO;

namespace Heyo.Class.Helper
{
    public static class DirectoryHelper
    {
        /// <summary>
        ///     拷贝文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="des"></param>
        public static void CopyDirectory(string src, string des)
        {
            string folderName = src.Substring(src.LastIndexOf("\\", StringComparison.Ordinal) + 1);

            string desFolderDir = des + "\\" + folderName;

            if (des.LastIndexOf("\\", StringComparison.Ordinal) == des.Length - 1) desFolderDir = des + folderName;
            string[] fileNames = Directory.GetFileSystemEntries(src);

            foreach (string file in fileNames) // 遍历所有的文件和目录
                if (Directory.Exists(file)) // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                {
                    string currentDir = desFolderDir + "\\" +
                                        file.Substring(file.LastIndexOf("\\", StringComparison.Ordinal) + 1);
                    if (!Directory.Exists(currentDir)) Directory.CreateDirectory(currentDir);
                    CopyDirectory(file, desFolderDir);
                }

                else // 否则直接copy文件
                {
                    string srcFileName = file.Substring(file.LastIndexOf("\\", StringComparison.Ordinal) + 1);
                    srcFileName = desFolderDir + "\\" + srcFileName;

                    if (!Directory.Exists(desFolderDir)) Directory.CreateDirectory(desFolderDir);
                    if (!File.Exists(srcFileName)) File.Copy(file, srcFileName, true);
                }
        }
    }
}